package com.chaofan.kings_poster.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.*;
import cn.hutool.http.HttpUtil;
import com.chaofan.kings_poster.common.RestfulMessage;
import com.chaofan.kings_poster.model.Hero;
import com.chaofan.kings_poster.model.RankingList;
import com.chaofan.kings_poster.model.Skin;
import com.chaofan.kings_poster.util.ImgUrlUtil;
import com.chaofan.kings_poster.util.RootApis;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * Created by Chaofan at 2018-12-10 15:26
 * email:chaofan2685@qq.com
 **/

@RestController
@RequestMapping("/api")
public class DownloadController extends RootApis {

    public static List<RankingList> RANKING_LISTS = new ArrayList<>();

    static {
        RANKING_LISTS.add(new RankingList("http://shp.qpic.cn/ishow/2735120415/1543906900_-888937974_10897_sProdImgNo_6.jpg/0",3));
        RANKING_LISTS.add(new RankingList("https://shp.qpic.cn/ishow/2735102310/1540260913_730872330_5548_sProdImgNo_6.jpg/0",2));
        RANKING_LISTS.add(new RankingList("https://shp.qpic.cn/ishow/2735013018/1517309037_84828260_13443_sProdImgNo_6.jpg/0",1));
    }

    @Value(value = "${skin.downloadPash}")
    private String downloadPash;

    @Value(value = "${skin.zipPash}")
    private String zipPash;

    @Value(value = "${download.size}")
    private String downloadSize;

    /**
     * 将搜索结果所得照片进行打包
     * @param name
     * @return
     */
    @GetMapping("/zip")
    public RestfulMessage zip(String name){
        //校验存储地址
        checkoutPash();
        List<Skin> skinList = requestApi(name);
        File[] skinNames = new File[skinList.size()];
        int i = 0;
        for (Skin skin : skinList){
            String skinName = skin.getName();
            Map<String,String> map = skin.getsProdImgNo();
            for (Map.Entry<String,String> entry : map.entrySet()) {
                skinNames[i] = FileUtil.file(downloadPash+"/"+skinName);
                File skinFile = FileUtil.file(downloadPash+"/"+skinName+"/"+entry.getKey()+".jpg");
                if (!skinFile.exists()){
                    HttpUtil.downloadFile(URLUtil.decode(ImgUrlUtil.switch200(entry.getValue().toString())), skinFile);
                }
            }
            i+=1;
        }
        String zipName = zipPash+"/("+ IdUtil.randomUUID()+")"+name+".zip";
        File zip = FileUtil.file(zipName);
        Assert.isTrue(skinNames.length>0,"未找到相关皮肤！");
        ZipUtil.zip(zip,true, skinNames);
        return buildResultData(URLUtil.encode(zipName));
    }

    /**
     * 下载打包好的原画
     * @param zipPash
     * @param response
     */
    @GetMapping("/download")
    public void download(String zipPash, HttpServletResponse response) {
        File zip = FileUtil.file(URLUtil.decode(zipPash));
        exportZip(response,zip);
    }


    /**
     * 搜索原画
     * @param name
     * @return
     */
    @GetMapping("/search")
    public RestfulMessage search(String name) {
        List<Skin> list = requestApi(name);
        Assert.isFalse(list.size()==0,"未找到相关原画！");
        List<Map<String,Object>> data = new ArrayList<>();
        for (Skin skin : list){
            Map<String,Object> result = new HashMap<>();
            result.put("name",skin.getName());
            result.put("cover",skin.getsProdImgNo_3());
            StringBuffer html = new StringBuffer();
            Map<String,String> skins = skin.getsProdImgNo();
            for (int j=2;j<9;j++){
                html.append("<div style='margin: 50px;text-align: center;'><img src='").append(skins.get("sProdImgNo_"+j)).append("' style='width: 60%'></div>");
            }
            result.put("list",html.toString());
            data.add(result);
            //TODO 实验性代码
            if (StrUtil.isNotEmpty(name)){
                String url = skins.get("sProdImgNo_6");
                Boolean flag = true;
                for (RankingList rankingList : RANKING_LISTS){
                    if (rankingList.cover.equals(url)){
                        rankingList.count+=1;
                        flag = false;
                    }
                }
                if (flag){
                    RANKING_LISTS.add(new RankingList(url,1));
                }
            }
        }
        Assert.isTrue(data.size()>0,"未找到相关皮肤！");
        return buildResultData(data);
    }

    /**
     * 删除压缩包路径下的所有压缩包
     * @return
     */
    @GetMapping("/deleteZip")
    public RestfulMessage deleteZip() {
        checkoutPash();
        File download = FileUtil.file(zipPash);
        if (download.exists()){
            FileUtil.del(download);
        }
        if (!download.exists()){
            return buildResultData(null);
        }else {
            return buildErrorResultData("删除失败！");
        }
    }

    /**
     * 获取所有英雄名称及其皮肤名称
     * @return
     */
    @GetMapping("/download/all")
    public RestfulMessage downloadAll() {
        List<String> errorList = new ArrayList<>();
        List<Hero> heroes = requestApi();
        String[] sizes = {"sProdImgNo_1","sProdImgNo_2","sProdImgNo_3","sProdImgNo_4","sProdImgNo_5","sProdImgNo_6","sProdImgNo_7","sProdImgNo_8"};
        List<String> downloadSizes = Arrays.asList(sizes);
        if (StrUtil.isEmpty(downloadSize) || !(downloadSizes.contains(downloadSize))){
            downloadSize = "sProdImgNo_";
        }
        for (Hero hero : heroes){
            errorList.addAll(downloadImg(hero.getName(),downloadSize));
        }
        return buildResultData(errorList);
    }



    /**
     * 检查配置文件中是否配置了下载路径和打包路径
     */
    private void checkoutPash(){
        if (StrUtil.isEmpty(downloadPash)){
            downloadPash = getDownloadPash();
        }
        if (StrUtil.isEmpty(zipPash)){
            zipPash = getZipPash();
        }
    }

    public List<String> downloadImg(String name, String downloadSize){
        //校验存储地址
        checkoutPash();
        return downloadImgs(name,downloadSize);
    }
}
